package com.bdqn.qnnews.user.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.qnnews.common.base.ResultCode;
import com.bdqn.qnnews.jwt.utils.JwtTokenUtil;
import com.bdqn.qnnews.rest.exception.ApplicationException;
import com.bdqn.qnnews.user.api.dto.ApUserDto;
import com.bdqn.qnnews.user.convert.ApUserConvert;
import com.bdqn.qnnews.user.entity.ApUser;
import com.bdqn.qnnews.user.mapper.ApUserMapper;
import com.bdqn.qnnews.user.service.ApUserService;
import com.bdqn.qnnews.user.vo.LoginReqVo;
import com.bdqn.qnnews.user.vo.UserRespVo;
import com.nimbusds.jose.JOSEException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author xlz
 * @since 2023-12-19
 */
@RequiredArgsConstructor
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    private final PasswordEncoder passwordEncoder;

    @Override
    public UserRespVo login(LoginReqVo loginReqVo) {
        // 判断是用户登录还是游客
        if (StringUtils.hasLength(loginReqVo.getPhone())
                && StringUtils.hasLength(loginReqVo.getPassword())){
            // 用户登录
            // 查询用户是否存在
            final QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", loginReqVo.getPhone());
            final ApUser user = getOne(queryWrapper);
            // 判断当前用户是否存在
            if (user == null){
                throw new ApplicationException(ResultCode.SYSTEM_USERNAME_NOT_EXISTS);
            }
            // 判断密码是否正确,这里需要使用加密工具进行校验, 注意取反
            if (!passwordEncoder.matches(loginReqVo.getPassword(),user.getPassword())){
                throw new ApplicationException(ResultCode.LOGIN_PASSWORD_ERROR);
            }

            // 生成token
            // 将查询得到的entity 转换为 Dto
            final ApUserDto apUserDto = ApUserConvert.INSTANCE.entityToDto(user);

            // 将用户信息转换为json字符串后传递给工具类生成token
            try {
                final String token = JwtTokenUtil.generateTokenByRsa(JSONUtil.toJsonStr(apUserDto), 60 * 60);
                // 将token和user对象封装为UserDto
                return new UserRespVo(token,apUserDto);
            } catch (JOSEException e) {
                throw new RuntimeException(e);
            }
        }else {
            // 游客登录
            // 创建一个空用户，设置id为0
            final ApUserDto apUserDto = new ApUserDto();
            apUserDto.setId(0);
            try {
                final String token = JwtTokenUtil.generateTokenByRsa(JSONUtil.toJsonStr(apUserDto), 24 * 60 * 60);
                // 将token和user对象封装为UserDto
                return new UserRespVo(token,null);
            } catch (JOSEException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
